import request from '@/utils/request'

// 查询商品自提点列表
export function listGoodsCenters(query) {
  return request({
    url: '/shop/goodsCenters/list',
    method: 'get',
    params: query
  })
}

// 查询商品自提点列表
export function listGoodsCentersAll(query) {
  return request({
    url: '/shop/goodsCenters/listAll',
    method: 'get',
    params: query
  })
}

// 查询商品自提点详细
export function getGoodsCenters(id) {
  return request({
    url: '/shop/goodsCenters/' + id,
    method: 'get'
  })
}

// 新增商品自提点
export function addGoodsCenters(data) {
  return request({
    url: '/shop/goodsCenters',
    method: 'post',
    data: data
  })
}

// 修改商品自提点
export function updateGoodsCenters(data) {
  return request({
    url: '/shop/goodsCenters',
    method: 'put',
    data: data
  })
}

// 删除商品自提点
export function delGoodsCenters(id) {
  return request({
    url: '/shop/goodsCenters/' + id,
    method: 'delete'
  })
}

/**
 * 生成 省市区 多层级下拉框数据
 *
 */
export function handleRegionCascader(data, id, name, parentId, children) {
  let regionTree = JSON.parse(localStorage.getItem("REGION_MAP")) || {};
  // let regionTree = {};
  let config = {
    id: id || 'id',
    name: name || 'name',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    let t = {value: d[config.id], label: d[config.name]}
    nodeIds[d[config.id]] = t;
    childrenListMap[parentId].push(t);
    if (!regionTree[d[config.id]]) {
      regionTree[d[config.id]] = d[config.name];
    }
  }
  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      let t = {value: d[config.id], label: d[config.name]}
      tree.push(t);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o.value] !== null) {
      o[config.childrenList] = childrenListMap[o.value];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  localStorage.setItem("REGION_MAP", JSON.stringify(regionTree));
  return tree;
}
